package com.nineclock.document.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.doc.pojo.DocFile;
import com.nineclock.document.dto.DocFileDto;
import com.nineclock.document.dto.DocFileHistoryDto;
import com.nineclock.document.dto.DocFolderDto;
import com.nineclock.document.dto.DocumentDto;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileHistoryMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.pojo.DocCollaborations;

import com.nineclock.document.pojo.DocFileHistory;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.DocService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DocServiceImpl implements DocService {

    @Autowired
    DocFolderMapper docFolderMapper;
    @Autowired
    DocFileMapper docFileMapper;
    @Autowired
    DocFileHistoryMapper docFileHistoryMapper;
    @Autowired
    DocCollaborationsMapper docCollaborationsMapper;
    @Autowired
    SysUserFeign userFeign;

    @Override
    public DocumentDto listFolderAndFIle(Long parentFoldId, String keyword) {
        //定义返回值对象
        DocumentDto documentDto = new DocumentDto();
        List<DocFolderDto> docFolderDtos = null;
        List<DocFileDto> docFileDtos = null;

        //查询文件夹列表
        LambdaQueryWrapper<DocFolder> folderWapper = new LambdaQueryWrapper<>();
        //构建查询条件
        folderWapper.eq(DocFolder::getCompanyId, CurrentUserHolder.get().getCompanyId());

        folderWapper.eq(DocFolder::getParentId, parentFoldId);
        folderWapper.eq(DocFolder::getStatus, 1);

        folderWapper.eq(DocFolder::getParentId, parentFoldId);

        //判断是否存在keyword
        if (StrUtil.isNotEmpty(keyword)) {
            folderWapper.like(DocFolder::getName, keyword);
        }
        List<DocFolder> docFolderList = docFolderMapper.selectList(folderWapper);
        if (CollectionUtil.isNotEmpty(docFolderList)) {
            docFolderDtos = BeanHelper.copyWithCollection(docFolderList, DocFolderDto.class);
        }


        //查询文件列表

        LambdaQueryWrapper<DocFile> fileWrapper = new LambdaQueryWrapper<>();
        fileWrapper.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        fileWrapper.eq(DocFile::getFolderId, parentFoldId);
        fileWrapper.eq(DocFile::getStatus, 1);
        fileWrapper.and(fileWrapper1 -> {
            fileWrapper1.eq(DocFile::getPermission, 0)
                    .or().eq(DocFile::getPermission, 1)
                    .or().eq(DocFile::getCreateUserId, CurrentUserHolder.get().getId());

        });

        if (StrUtil.isNotEmpty(keyword)) {
            fileWrapper.like(DocFile::getName, keyword);
        }
        List<DocFile> docFiles = docFileMapper.selectList(fileWrapper);
        if (CollectionUtil.isNotEmpty(docFiles)) {
            docFileDtos = BeanHelper.copyWithCollection(docFiles, DocFileDto.class);
            //每个文件都关联两部分内容，DocCollaborations，DocFileHistory
            for (DocFileDto docFileDto : docFileDtos) {
                //根据fileId 查询协作者信息列表
                List<SysCompanyUserDTO> data = null;
                LambdaQueryWrapper<DocCollaborations> DCwrapper = new LambdaQueryWrapper<>();
                DCwrapper.eq(DocCollaborations::getFileId, docFileDto.getId());
                List<DocCollaborations> docCollaborations = docCollaborationsMapper.selectList(DCwrapper);
                //处理协作者集合
                if (CollectionUtil.isNotEmpty(docCollaborations)) {
                    List<Long> ids = docCollaborations.stream()
                            .map(docCollaborations1 -> {
                                return docCollaborations1.getCollaborationId();
                            })
                            .collect(Collectors.toList());
                    //根据拿到的ids调用远程接口查询用户列表
                    data = userFeign.queryCompanyUserByIds(ids).getData();
                }
                if (CollectionUtil.isNotEmpty(data)) {
                    docFileDto.setCollaborations(data);
                }
                //根据创建者ID，查询创建者信息
                List<Long> id = new ArrayList<>();
                id.add(CurrentUserHolder.get().getId());
                List<SysCompanyUserDTO> creator = userFeign.queryCompanyUserByIds(id).getData();
                SysCompanyUserDTO companyUserDTO = creator.get(0);
                docFileDto.setCreator(companyUserDTO);
                //封装最后一个更新人的姓名
                LambdaQueryWrapper<DocFileHistory> historyLambdaQueryWrapper = new LambdaQueryWrapper<>();
                historyLambdaQueryWrapper.eq(DocFileHistory::getFileId, docFileDto.getId());
                List<DocFileHistory> docFileHistories = docFileHistoryMapper.selectList(historyLambdaQueryWrapper);
                if (CollectionUtil.isNotEmpty(docFileHistories)) {
                    DocFileHistory docFileHistory = docFileHistories.get(docFileHistories.size() - 1);
                    Long operateUserId = docFileHistory.getOperateUserId();
                    if (data != null) {
                        List<SysCompanyUserDTO> collect = data.stream().filter(operate -> {
                            return operate.getId() != operateUserId;
                        }).collect(Collectors.toList());
                        String lastOperator = collect.get(0).getUserName();
                        //封装用户名
                        docFileDto.setUserName(companyUserDTO.getUserName());
                    }
                }
            }
        }


        //封装返回值对象
        documentDto.setFolders(docFolderDtos);
        documentDto.setFiles(docFileDtos);
        return documentDto;
    }



    @Override
    public void banOrLift(Long fileId, Short status) {
        if (fileId == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        if (status == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //参数不为空，开始查询文件并且更新文件状态
        LambdaQueryWrapper<DocFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(DocFile::getId, fileId);
        DocFile docFile = docFileMapper.selectOne(wrapper);
        if (docFile == null) {
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }
        docFile.setStatus(status);
        docFileMapper.updateById(docFile);

        //更改完成后新增文件记录表
        DocFileHistory docFileHistory = new DocFileHistory();
        //设置字段
        docFileHistory.setFileId(docFile.getId());
        docFileHistory.setFileName(docFile.getName());
        docFileHistory.setIsCreate((short) 0);
        docFileHistory.setContent(docFile.getContent());
        docFileHistory.setOperateTime(new Date());
        docFileHistory.setOperateUserId(CurrentUserHolder.get().getId());

        docFileHistoryMapper.insert(docFileHistory);
    }

    /**
     * 查询文件历史记录
     *
     * @param field
     * @return
     */
    @Override
    public List<DocFileHistoryDto> queryhistory(Long field) {
        LambdaQueryWrapper<DocFileHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFileHistory::getFileId, field);
        List<DocFileHistory> list = docFileHistoryMapper.selectList(wrapper);
        return BeanHelper.copyWithCollection(list, DocFileHistoryDto.class);
    }

}